package com.ssyc.student.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentChooseQuestionTypeActivity;
import com.ssyc.student.activity.StudentShowTextAnswerActivity;
import com.ssyc.student.activity.StudentTextPrepareActivity;
import com.ssyc.student.adapter.StRvChooseAnswerAdapter;
import com.ssyc.student.bean.ChooseAnswerInfo;
import com.ssyc.student.bean.CommitInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.TextPrepareInfo;
import com.ssyc.student.util.CommitUtil;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--课文预习完成--提交界面
 * Created by Administrator on 2018/5/10 0010.
 */

public class StudentTextCommitFragment extends LazyBaseFragment implements View.OnClickListener {

    //题目是否完成的提示语
    //1、用户完成了所有的题提示语为：完成啦，提交吧
    //2、用户还有题未做完提示语未
    private TextView tvStateMsg;

    //展示所有题目状态的列表
    private MyGridView gv;

    //展示答题的列表的数据集合
    private List<ChooseAnswerInfo> chooseAnswerInfos;

    //保存用户答题的正确或者错误的集合
    private List<ChooseAnswerInfo> answerInfos;

    //提交按钮
    private Button btCommit;
    private StRvChooseAnswerAdapter adapter;

    //Activity中用于保存用户答题状态的集合
    private Map<Integer, String> chooseAnswerMap;

    //Acivity中用于保存用户答题正确或者错误的集合
    private Map<Integer, Boolean> answerMap;

    //重新做题后的标识
    public static String HASDONE = "hasdown";

    //是否允许提交答案的标识,默认是可以提交的
    private boolean hasCommit = false;

    //LessonId和gradeId
    private String lessonId, gradeId;

    //所有问题的集合
    List<TextPrepareInfo.DataBean.QuestionListBean> question_list;

    public static StudentTextCommitFragment studentTextCommitFragment;

    public static StudentTextCommitFragment newInstance(String listJson, String lessonId, String gradeId) {
        studentTextCommitFragment = new StudentTextCommitFragment();
        Bundle bundle = new Bundle();
        bundle.putString("listjson", listJson);
        bundle.putString("lessonId", lessonId);
        bundle.putString("gradeid", gradeId);
        studentTextCommitFragment.setArguments(bundle);
        return studentTextCommitFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_read_commit;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        showContent();
        initView(view);
        //获取页面数据
        initData();
        //设置提示文字信息需要显示的文字
        initMsg();
        //设置展示列表
        initRv();
    }

    /**
     * 初始化View
     *
     * @param view
     */
    public void initView(View view) {
        tvStateMsg = view.findViewById(R.id.tv_state_msg);
        gv = view.findViewById(R.id.gv);
        btCommit = view.findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(this);
    }

    /**
     * 设置展示列表数据
     */
    private void initRv() {
        adapter = new StRvChooseAnswerAdapter(getContext(), chooseAnswerInfos, R.layout.student_rv_choose_answer);
        gv.setAdapter(adapter);
    }

    /**
     * 获取页面数据
     */
    private void initData() {
        //获取LessonId,GradeId,和Question的集合
        lessonId = getArguments().getString("lessonId");
        gradeId = getArguments().getString("gradeid");

        //获取整个问题集合的json数据
        String questionListJson = getArguments().getString("listjson");
        if (!TextUtils.isEmpty(questionListJson)) {
            question_list = GsonUtil.jsonToList(questionListJson, TextPrepareInfo.DataBean.QuestionListBean[].class);
        }
        chooseAnswerInfos = new ArrayList<>();
        chooseAnswerMap = StudentTextPrepareActivity.getChooseAnswerMap();
        //遍历Map取出需要展示的选择题的答案
        for (Map.Entry<Integer, String> entry : chooseAnswerMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            ChooseAnswerInfo info = new ChooseAnswerInfo();
            info.answerIndex = entry.getKey() + 1;
            info.answerFlag = entry.getValue();
            chooseAnswerInfos.add(info);
        }
    }


    /**
     * 设置提示信息需要显示的文字
     */
    private void initMsg() {
        if (hasChooseAnswer()) {
            tvStateMsg.setText("完成啦,提交吧!");
        } else {
            tvStateMsg.setText("请完成题目后在提交");
        }
    }


    /**
     * 判断是否全部答题的方法
     *
     * @return
     */
    public boolean hasChooseAnswer() {
        boolean res = true;
        for (int i = 0; i < chooseAnswerInfos.size(); i++) {
            if (TextUtils.isEmpty(chooseAnswerInfos.get(i).answerFlag)) {
                res = false;
                break;
            }
        }

        return res;
    }

    /**
     * 处理重新做题后的事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.msg != null && busInfo.msg.equals(HASDONE)) {
            chooseAnswerInfos.get(busInfo.pos).setAnswerFlag(busInfo.answerFlag);
            adapter.notifyDataSetChanged();
        } else if (null != busInfo && StudentShowTextAnswerActivity.LOOKANSWER == busInfo.getType()) {
            hasCommit = true;
        }
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.bt_commit) {
            //提交答案
            doCommitAction();
        }
    }

    /**
     * 提交答案的操作
     */
    private void doCommitAction() {
        //首先判断是否已经提交过
        if (hasCommit) {
            UiUtils.Toast("查看答案模式下不能提交答案", false);
            return;
        } else {
            //提交
            if (hasChooseAnswer()) {
                //跳转到展示阅读答题结果的界面,这里还需要上传服务器,同时需要通过将Activity的计时时间携带给下个界面
                doCommitScoreHttp();

            } else {
                UiUtils.Toast("请完成题目后在提交", false);
                return;
            }
        }
    }

    /**
     * 上传做题的答案给服务器
     */
    private void doCommitScoreHttp() {

        CustomDialogManager.show(getContext(), "上传中...");

        CommitInfo commitInfo = new CommitInfo();

        //级别
        commitInfo.setGrade_id(gradeId);

        //课程编号
        commitInfo.setLesson_id(lessonId);

        //模块编号
        commitInfo.setModule_id("11");

        //题目总数量
        commitInfo.setAmount(question_list.size() + "");

        //正确题目数量
        commitInfo.setAmount_t(CommitUtil.getRightAnswerCount(StudentTextPrepareActivity.getAnswerMap()) + "");

        //总分
        commitInfo.setScore("0");

        //得分
        commitInfo.setScore_t("0");

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        commitInfo.setSeconds(seconds);

        List<CommitInfo.SubjectBean> subjectBeans = new ArrayList<>();
        for (int i = 0; i < question_list.size(); i++) {

            CommitInfo.SubjectBean subjectBean = new CommitInfo.SubjectBean();

            //题目编号
            subjectBean.setQuestion_id(question_list.get(i).getTitle() + "");

            //题型编号
            subjectBean.setType_id(question_list.get(i).getTitletype() + "");

            //正确与否
            if (StudentTextPrepareActivity.getAnswerMap().get(i) == true) {
                subjectBean.setResult("1");
            } else {
                subjectBean.setResult("0");
            }

            //填空内容
            //获取选择的索引值,这里计算的规则是:宿主Activity中ChooseAnswerMap中保存了用户选择的所有选项,索引对应字母
            int index = CommitUtil.getChooseAnswerIndex(getContext(), i, StudentTextPrepareActivity.getChooseAnswerMap());
            subjectBean.setContent(question_list.get(i).getJpglist().get(index).getText());

            //得分
            subjectBean.setScore("0");

            subjectBeans.add(subjectBean);
        }

        commitInfo.setSubject(subjectBeans);

        //转换成JSON字符串
        String postServerJson = GsonUtil.objectToJson(commitInfo);

        Log.i("test", "上传给服务器的JSON是:" + postServerJson);

        Map<String, String> map = new HashMap<>();
        map.put("type", "24");
        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("studys", postServerJson);
        map.put("apptoken", AccountUtils.getToken(getContext()));
        map.put("platform", "8");

        if (TextUtils.isEmpty(RecordTimeUtil.energy)) {
            map.put("energy", "0");
        } else {
            map.put("energy", RecordTimeUtil.energy);
        }

        HttpUtils.post(HttpAdress.COMMITSCORE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                CustomDialogManager.dissmiss();

                ResultInfo info = null;

                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //发送已经做完的更新
                            BusInfo stateInfo = new BusInfo();
                            stateInfo.setType(StudentChooseQuestionTypeActivity.UPDATAPAGESTATE);
                            EventBus.getDefault().post(stateInfo);
                            //提交成功后跳转到下个界面
                            goToShowAnswerActivity();
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });
    }

    /**
     * 跳转到阅读答案展示界面的Acitivity
     */
    private void goToShowAnswerActivity() {
        //改变允许提交的值
        hasCommit = true;
        Intent intent = new Intent(getContext(), StudentShowTextAnswerActivity.class);
        //携带倒计时时间
        //携带答题的正确和错误的数据集合
        answerInfos = new ArrayList<>();
        answerMap = StudentTextPrepareActivity.getAnswerMap();
        //遍历Map取出需要展示的选择题的答案
        for (Map.Entry<Integer, Boolean> entry : answerMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            ChooseAnswerInfo info = new ChooseAnswerInfo();
            info.answerIndex = entry.getKey() + 1;
            info.isCorrect = entry.getValue();
            answerInfos.add(info);
        }

        intent.putExtra("data", GsonUtil.listToJson(answerInfos));

        //传递第一次进入的时间
        intent.putExtra(StudentShowTextAnswerActivity.FIRSTTIME, StudentTextPrepareActivity.getFirstTime());
        startActivity(intent);
    }


}
